﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NetC100K;
using NetC100KTest.Command;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace NetC100KTest
{
    internal class HeartbeatHostedService : IHostedService
    {
        private ILogger _logger;
        private SessionPool _sessionPool;
        private CancellationTokenSource _cts;

        public HeartbeatHostedService(SessionPool sessionPool, ILogger<HeartbeatHostedService> logger)
        {
            _sessionPool = sessionPool;
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _cts = new CancellationTokenSource();
            Task.Run(async () =>
            {
                while (!_cts.IsCancellationRequested)
                {
                    await Task.Delay(30 * 1000);

                    _logger.LogInformation("定时数据开始发送......");
                    var options = new System.Text.Json.JsonSerializerOptions()
                    {
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                    };
                    _sessionPool.ConcurrentSend((channel) =>
                    {
                        HeartbeatRequest request = new HeartbeatRequest()
                        {
                            Datetime = DateTime.Now,
                            Message = "汉字测试"
                        };
                        return JsonSerializer.Serialize<HeartbeatRequest>(request, options);
                    });
                    _logger.LogInformation($"定时数据发送完成，现有连接数：{_sessionPool.Channels.Count}......");
                }
            }, _cts.Token);
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
